package com.home.cca.adapters;

import static java.util.concurrent.CompletableFuture.runAsync;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.home.cca.R;
import com.home.cca.model.Goods;
import com.home.cca.network.UpdateGoodsRequest;

import java.util.Locale;
import java.util.function.Consumer;

public class GoodsViewHolder extends RecyclerView.ViewHolder {
    private final TextView tvName, tvPrice, tvStock;
    private Consumer<String> toast;

    public GoodsViewHolder(@NonNull View itemView) {
        super(itemView);
        tvName = itemView.findViewById(R.id.goodsName);
        tvPrice = itemView.findViewById(R.id.tvPrice);
        tvStock = itemView.findViewById(R.id.tvStock);

        // 设置点击事件
        tvPrice.setOnClickListener(v1 -> showInputDialog("价格", tvPrice.getText().toString(), tvPrice));
        tvStock.setOnClickListener(v1 -> showInputDialog("库存", tvStock.getText().toString(), tvStock));
    }

    public void bind(Goods goods, Consumer<String> toast) {
        this.toast = toast;

        // 设置名称
        tvName.setText(goods.getName());
        tvPrice.setText(String.format(Locale.getDefault(), "%.1f", goods.getPrice()));
        tvStock.setText(String.valueOf((int) goods.getStorageQty()));

        // 用于在 TextWatcher 中获取当前商品
        itemView.setTag(goods);
    }

    private void showInputDialog(String title, String currentValue, TextView tv) {
        AlertDialog.Builder builder = new AlertDialog.Builder(tv.getContext());
        EditText input = new EditText(tv.getContext());
        input.setText(currentValue);
        input.setInputType(title.equals("价格") ?
                InputType.TYPE_NUMBER_FLAG_DECIMAL :
                InputType.TYPE_CLASS_NUMBER);

        builder.setTitle("修改" + title)
                .setView(input);

        // ❌ 不要直接 show()，我们要控制按钮
        AlertDialog dialog = builder.create();

        // 自定义取消按钮
        dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", (d, which) -> {
            d.dismiss(); // 取消直接关闭
        });

        // 自定义确认按钮（不自动关闭）
        dialog.setButton(AlertDialog.BUTTON_POSITIVE, "确认", (DialogInterface.OnClickListener) null);

        // 显示后设置点击事件，避免点击后自动关闭
        dialog.setOnShowListener(d -> {
            Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(v -> {
                String value = input.getText().toString().trim();
                if (value.isEmpty()) {
                    toast.accept("请输入有效值");
                    return;
                }

                // 更新 UI 显示（可选：先改本地显示）
                tv.setText(value);

                // 获取数据源
                Goods goods = (Goods) itemView.getTag();
                if (title.equals("价格")) {
                    goods.setPrice(Double.parseDouble(value));
                } else {
                    goods.setStorageQty(Integer.parseInt(value));
                }

                // ✅ 在子线程执行网络请求
                runAsync(() -> {
                    try {
                        UpdateGoodsRequest.update(goods); // 同步网络请求
                        // 回到主线程提示成功
                        tv.post(() -> toast.accept(title + "修改成功"));
                    } catch (Exception e) {
                        tv.post(() -> toast.accept("更新失败: " + e.getMessage()));
                    } finally {
                        // ✅ 无论成功失败，最后都关闭弹框
                        tv.post(dialog::dismiss);
                    }
                });
            });
        });

        // 显示对话框
        dialog.show();
    }
}